<?php

//小说管理
class BookController extends Controller
{
	//小说列表
	public function actionList()
	{
		$criteria 	= new CDbCriteria();
		if (isset($_GET['search']))
		{
			if (! empty($_GET['book_id']))
				$criteria->addCondition('book_id='.$_GET['book_id']);
			if (! empty($_GET['book_title']))
				$criteria->addCondition('book_title like "%'.$_GET['book_title'].'%"');
			if (! empty($_GET['book_author']))
				$criteria->addCondition('book_author="'.$_GET['book_author'].'"');
		}
		$count 		= Book::model()->count($criteria);
		$pages		= new CPagination($count);
		$pages->pageSize = 10;
		$pages->applyLimit($criteria);
		$bookModel = Book::model()->findAll($criteria);
		$this->render('list', array('bookModel'=>$bookModel,'pages'=>$pages));
	}

	//新增小说
	public function actionAdd()
	{
		$bookModel = new Book;
		
		if (isset($_POST['Book']))
		{
			$bookModel->attributes = $_POST['Book'];
			if ($bookModel->save())
			{
				$this->success('',Yii::app()->createUrl('admin/book/list'));
			}else{
				$this->error($bookModel->getErrors());
			}
		}
		$bookModel->setAttribute('book_status', '1');
		$this->render('add',array(
			'model'	=> $bookModel
		));
	}
	
	//修改小说
	public function actionEdit()
	{
		$bookModel = Book::model()->findByPk($_GET['book_id']);
		
		if (isset($_POST['Book']))
		{
			$bookModel->attributes = $_POST['Book'];
			if ($bookModel->save())
			{
				$this->success();
			}else{
				$this->error($bookModel->getErrors());
			}
		}
		
		$bookModel->book_finish_time = date('Y-m-d',$bookModel->book_finish_time);
		$this->render('edit',array(
			'model'	=> $bookModel
		));
	}
	
	//删除小说
	public function actionDelete()
	{
		echo Book::model()->deleteByPk($_POST['book_id']);
		Yii::app()->end();
	}
	
	//自动完成
	public function actionGetTitle()
	{
		$models = Book::model()->findAll(array('select'=>'book_title', 'limit'=>'6', 'condition'=>'book_title like "%'.$_GET['term'].'%"'));
		$data = array();
		foreach ($models as $model)
		{
			$data[] = $model->book_title;
		}
		echo json_encode($data);
		Yii::app()->end();
	}
}
